package com.dx.service.user.impl;

import com.dx.cache.Cache;
import com.dx.entity.user.User;
import com.dx.enums.CacheNameEnum;
import com.dx.mapper.user.UserMapper;
import com.dx.model.ApiResult;
import com.dx.model.user.bo.LoginBO;
import com.dx.security.dto.AccessToken;
import com.dx.security.provider.JwtProvider;
import com.dx.service.user.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YU.TAN
 * @since 2023-07-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtProvider jwtProvider;
    @Autowired
    private Cache caffeineCache;

    @Override
    public ApiResult login(LoginBO loginBO) {
        log.debug("进入login方法");
        // 1 创建UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBO.getLoginAccount(), loginBO.getPassword());
        Map<String,String> map =new HashMap<>();
        map.put("userType",loginBO.getTenantId().toString());
        authenticationToken.setDetails(map);
        // 2 认证
        Authentication authenticate = this.authenticationManager.authenticate(authenticationToken);
        // 3 保存认证信息
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        // 4 生成自定义token
        UserDetails userDetails = (UserDetails) authenticate.getPrincipal();
        AccessToken token = jwtProvider.createToken(userDetails);
        // 放入缓存
        caffeineCache.put(CacheNameEnum.USER, userDetails.getUsername(), userDetails);
        return ApiResult.ok(token);
    }
}
